<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use think\Request;

class Order extends Backend
{
	
	public function __construct()
	{
		parent::__construct();

		$this->OrderModel = model('Product.Order');

		$this->OrderProductModel = model('Product.OrderProduct');
		
		$this->CartModel = model('Product.Cart');

		$this->UserModel = model('User.User');

		$this->RecordModel = model('User.Record');

		$this->ProductModel = model('Product.Product');
	}
	
	public function order(){
		
		$Orderlist = model('Product.Order')->with(['user','addres'])->order('id desc')->paginate(7,false,['query' => Request::instance()->param()]);
		
		return $this->fetch('',[
			
			'Orderlist' => $Orderlist
			
		]);
		
	}
	
	// 查看单条评论
	public function evaluation(){
		
		//订单id
		$orderid = $this->request->param('orderid');
		
		// userid
		$userid = $this->request->param('userid');
		
		$Order = $this->OrderModel->find($orderid);
		
		if(!$Order)
		{
			$this->error('查看失败，改售订单不存在');
		}
		
		$User = $this->UserModel->find($userid);
		
		if(!$User)
		{
			$this->error('查看失败，改用户不存在不存在');
		}
		
		if($Order['userid'] != $User['id'])
		{
			$this->error('查看失败，非法查看');
		}
		
		$productStr = '';
		
		$productImgArr = [];
		
		foreach($Order['order_cdn'] as $item)
		{
			foreach($item as $key => $val)
			{
				$productStr .= $val['name'] . '、';
				
				$productImgArr[] = [
					$key => $val['cover_cdn'],
				];
			}
		}
		
		$comment = $this->OrderProductModel->where('orderid',$Order['id'])->value('comment');
		
		$Porduct = $this->OrderProductModel->where('orderid',$Order['id'])->find();
		
		return $this->fetch('',[
			
			'User' => $User,
			
			'Order' => $Order,
			
			'productStr' => $productStr,
			
			'productImgArr' => $productImgArr,
			
			'comment' => $comment,
			
			'Porduct' => $Porduct
			
		]);
		
	}
	
	// 查询商品评分表
	public function orderproduct(){
		
		// 查询商品表
		$Orderductlist = model('Product.OrderProduct')->with(['product','user'])->order('id desc')->paginate(7,false,['query' => Request::instance()->param()]);
		
		return $this->fetch('',[
			
			'Orderductlist' => $Orderductlist
			
		]);
		
	}
	
	// 查看删除的订单
	public function prorestore(){
		// whereNotNull('belong')  'deletetime', 'is not null'
		$restorelist = model('Product.Order')->onlyTrashed()->paginate(7,false,['query' => Request::instance()->param()]);
		
		return $this->fetch('',[
			
			'restorelist' => $restorelist
			
		]);
		
	}
	
	// 查看删除的评论
	public function productrestore(){
		// whereNotNull('belong')  'deletetime', 'is not null'
		$restorelist = model('Product.OrderProduct')->onlyTrashed()->paginate(7,false,['query' => Request::instance()->param()]);
		
		return $this->fetch('',[
			
			'restorelist' => $restorelist
			
		]);
		
	}
	
	// 商品售后状态详情
	public function status()
	{
	    // 查询商品表['user','cate']
	    
	    $Statuslist = model('Product.Status')->order('id desc')->paginate(7,false,['query' => Request::instance()->param()]);
	    
	    
	    return $this->fetch('',[
	        
			'Statuslist' => $Statuslist
			
	    ]);
	}
	
	// 服务售后状态添加
	public function statusadd()
	{
		if($this->request->isPost())
		{
			// 状态昵称
			$name = $this->request->param('name');
			
			// 状态值
			$status = $this->request->param('status');
			
			$StatusList = model('Product.Status')->select();
			
			foreach($StatusList as $key => $val)
			{
				if($val['status'] == $status)
				{
					$this->error('添加失败，该售后值已经存在',url('admin/order/status'),null,1);
				}
			}
			
			// 封装数组
			$data = [
				'name' => $name,
				'status' => $status
			];
			
			// 验证
			$result = model('Product.Status')->validate('common/Project/Status')->save($data);
			
			if($result === FALSE)
			{
				$this->error('添加失败');	
			}else{
				// cookie('LoginUser',null);
				$this->success('添加成功',url('admin/order/status'),null,0);
			}
		}
		
		return $this->fetch('',[
			
		]);
	}
	
	// 编辑售后状态
	public function statusedit()
	{
		// 售后id
		$id = $this->request->param('id');
		
		$status = model('Product.Status')->find($id);
		
		if(!$status)
		{
			$this->error('编辑失败，改售后类型不存在');
		}
		
		if($this->request->isPost())
		{
			// 售后昵称
			$name = $this->request->param('name');
			
			// 售后状态
			$status = $this->request->param('status');
			
			$StatusList = model('Product.Status')->select();
			
			foreach($StatusList as $key => $val)
			{
				if($val['status'] == $status)
				{
					$this->error('编辑失败，该售后值已经存在',url('admin/order/status'),null,1);
				}
			}
			
			// 封装数组
			$data = [
				'id' => $id,
				'name' => $name,
				'status' => $status
			];
			
			// 验证
			$result = model('Product.Status')->isUpdate(true)->save($data);
			
			if($result === FALSE)
			{
				$this->error('编辑失败');	
			}else{
				// cookie('LoginUser',null);
				$this->success('编辑成功',url('admin/order/status'),null,0);
			}
			
		}
		
		return $this->fetch('',[
			
			'status' => $status
			
		]);
	}
	
	// 删除售后状态
	public function delstatus()
	{
		if($this->request->isAjax())
		{
			// id
			$id = $this->request->param('id');
			
			// 批量删除
			$str = $this->request->param('str');
			
			if(!empty($id))
			{
				// 查询
				$Status = model('Product.Status')->find($id);
				
				if(!$Status)
				{
					$this>error('删除失败，该售后状态不存在');
				}
				
				$result = model('Product.Status')->where('id',$id)->delete();
				
				if($result === FALSE)
				{
					$this->error('删除失败');
					
				}else{
					
					$this->success('删除成功','/admin/order/status');
				}
			}
			
			if(!empty($str))
			{
				// 查询
				$Status = model('Product.Status')->whereIn('id',$str)->select();
				
				if(!$Status)
				{
					$this>error('删除失败，该售后状态不存在');
				}
				
				$result = model('Product.Status')->whereIn('id',$str)->delete();
				
				if($result === FALSE)
				{
					
				    $this->error('删除失败');
				
				}else{
									
				    $this->success('删除成功','/admin/order/status');
					
				}
				
			}
			
		}
		
	}
	
	
	// 软删除评价
	public function delproduct()
	{
		if($this->request->isAjax())
		{
			// id
			$id = $this->request->param('id');
			
			// 批量删除
			$str = $this->request->param('str');
			
			if(!empty($id))
			{
				// 查询
				$Product = model('Product.OrderProduct')->find($id);
				
				if(!$Product)
				{
					$this>error('删除失败，该评论不存在');
				}
				
				$result = model('Product.OrderProduct')->destroy($id);
				
				if($result === FALSE)
				{
					$this->error('删除失败');
					
				}else{
					
					$this->success('删除成功','/admin/order/orderproduct');
				}
			}
			
			if(!empty($str))
			{
				// 查询
				$Product = model('Product.OrderProduct')->whereIn('id',$str)->select();
				
				if(!$Product)
				{
					$this>error('删除失败，该评论不存在');
				}
				
				$result = model('Product.OrderProduct')->destroy($str);
				
				if($result === FALSE)
				{
					
				    $this->error('删除失败');
				
				}else{
									
				    $this->success('删除成功','/admin/order/orderproduct');
					
				}
				
			}
			
		}
		
	}
	
	// 恢复删除的评论
	public function restoreproduct()
	{
		if($this->request->isAjax())
		{
			// id
			$id = $this->request->param('id');
			
			// 批量恢复
			$str = $this->request->param('str');
			
			if(!empty($id))
			{				
				// 封装数组
				$data = [
					'id' => $id,
					'deletetime' => null
				];
				
				$result = model('Product.OrderProduct')->isUpdate(true)->save($data);
				
				if($result === FALSE)
				{
					$this->error('恢复失败');
					
				}else{
					
					$this->success('恢复成功','/admin/order/orderproduct');
				}
			}
			
			if(!empty($str))
			{
				// 字符串转数组
				$arr = explode(',',$str);
				
				$data = [];
				
				// 循环
				foreach($arr as $item){
					$data[] = [
						'id' => $item,
						'deletetime' => null
					];
				}
				
				$result = model('Product.OrderProduct')->isUpdate(true)->saveAll($data);
				
				if($result === FALSE)
				{
					
				    $this->error('恢复失败');
				
				}else{
									
				    $this->success('恢复成功','/admin/order/orderproduct');
					
				}
				
			}
			
		}
		
	}
	
	// 恢复删除的订单
	public function restore(){
		
		if($this->request->isAjax()){
			
			// 获取启动数据
			$arrstr = $this->request->param('str');
			
			// 字符串转数组
			$arr = explode(',',$arrstr);
			
			$data = [];
			
			// 循环
			foreach($arr as $item){
				$data[] = [
					'id' => $item,
					'deletetime' => null
				];
			}
			
			$result = model('Product.Order')->isUpdate(true)->saveAll($data);
			
			if($result === FALSE)
			{
				$this->error('恢复失败');	
			}else{
				// cookie('LoginUser',null);
				$this->success('恢复成功',url('admin/Order/Order'),null,0);
			}
			
		}
		
	}
	
	// 软删除
	// 删除商品
	public function delorder()
	{
		if($this->request->isAjax())
		{
			// id
			$id = $this->request->param('id');
			
			// 批量删除
			$str = $this->request->param('str');
			
			if(!empty($id))
			{
				// 查询
				$Product = model('Product.Order')->find($id);
				
				if(!$Product)
				{
					$this>error('删除失败，该订单不存在');
				}
				
				$result = model('Product.Order')->destroy($id);
				
				if($result === FALSE)
				{
					$this->error('删除失败');
					
				}else{
					
					$this->success('删除成功','/admin/order/order');
				}
			}
			
			if(!empty($str))
			{
				// 查询
				$Product = model('Product.Order')->whereIn('id',$str)->select();
				
				if(!$Product)
				{
					$this>error('删除失败，该订单不存在');
				}
				
				$result = model('Product.Order')->destroy($str);
				
				if($result === FALSE)
				{
					
				    $this->error('删除失败');
				
				}else{
									
				    $this->success('删除成功','/admin/order/order');
					
				}
				
			}
			
		}
		
	}
	
	// 拒绝售后
	public function refuse()
	{
		$orderid = $this->request->param('id');
		
		// 订单
		$order = $this->OrderModel->find($orderid);
		
		if(!$order)
		{
		    $this->error('订单不存在，请重新选择');
		}
		
		$orderstatus = $this->request->param('status');
		
		$userid = $this->request->param('userid');
		
		$user = $this->UserModel->find($userid);
			
		if(!$user)
		{
		    $this->error('用户不存在，请重新注册');
		}
		
		if($order['userid'] != $user['id'])
		{
			$this->error('非法提交，请重新选择');
		}
		
		if(empty($orderstatus))
		{
			$this->error('请选择售后状态');
		}
		
		// 拒绝
		if($orderstatus == '-3')
		{
			
			// 封装数组
			$data = [
				'id' => $order['id'],
				'status' => -3
			];
			
			// 更新数据
			$result = $this->OrderModel->isUpdate(true)->save($data);
			
			if($result === FALSE)
			{
				$this->error('拒绝退货失败');	
			}else{
				// cookie('LoginUser',null);
				$this->success('拒绝退货成功','admin/order/order');
			}
			
		}elseif($orderstatus == '-1')
		{
			// 开启事务
			$this->UserModel->startTrans();
			$this->OrderModel->startTrans();
			
			// 用户更新数据
			$UserData = [
			    'id' => $user['id'],
			    'point' => bcadd($user['point'],$order['total'])
			];
			
			$UserStatus = $this->UserModel->isUpdate(true)->save($UserData);
			
			if($UserStatus === FALSE)
			{
			    $this->error($this->UserModel->getError());
			}
			
			
			$OrderData = [
				'id' => $order['id'],
				'status' => -1
			];
			
			$OrderStatus = $this->OrderModel->isUpdate(true)->save($OrderData);
			
			if($OrderStatus === FALSE)
			{
				$this->UserModel->rollback();
			    $this->error($this->OrderModel->getError());
			}
			
			if($OrderStatus === FALSE || $UserStatus === FALSE)
			{
				$this->OrderModel->rollback();
				$this->UserModel->rollback();
				$this->error('退货失败');
			}else{
				$this->OrderModel->commit();
				$this->UserModel->commit();
				$this->success('退货成功','admin/order/order');
			}
			
		}
		
	}
	
	// 售后详情
	public function aftersales()
	{
	    $userid = $this->request->param('userid');
	
	    $orderid = $this->request->param('orderid');
	
	    $user = $this->UserModel->find($userid);
	
	    if(!$user)
	    {
	        $this->error('用户不存在，请重新注册');
	    }
	
	    /* 
	        订单表
	        订单商品表 （主表）
	        商品表
	        用户收货地址
	    */
	
	    // 订单
	    $order = $this->OrderModel->find($orderid);
	
	    // 订单商品
	    $OrderProduct = $this->OrderProductModel->with('product')->where(['orderid' => $orderid])->select();
	
	    // 收货地址
	    $Address = model('User.Address')->with(['provinces','citys','districts'])->find($order['addrid']);
	    
	    if(!$order || !$OrderProduct || !$Address)
	    {
	        $this->error('订单不存在，请重新选择');
	    }
		
		if($order['status'] != '-2' || $orderid != $order['id'])
		{
			$this->error('非法修改，请重新选择');
		}
		
		// halt($OrderProduct[0]['product']['name']);
		$productStr = '';
		
		$productImgArr = [];
		
		foreach($order['order_cdn'] as $item)
		{
			foreach($item as $key => $val)
			{
				$productStr .= $val['name'] . '、';
				
				$productImgArr[] = [
					$key => $val['cover_cdn'],
				];
			}
		}
		
		return $this->fetch('',[
			'productStr' => $productStr,
			'productImgArr' => $productImgArr,
			'order' => $order,
			'OrderProduct' => $OrderProduct,
			'address' => $Address,
			'user' => $user
		]);
	
	}
	
	// 编辑单号
	public function orderedit()
	{
		// orderid
		$orderid = $this->request->param('id');
		
		//
		$Order = model('Product.Order')->find($orderid);
		
		// 收获地址
		$Address = model('User.Address')->where('id',$Order['addrid'])->find();
		
		$Region = model('Region')->where('code',$Address['district'])->find();
		
		$RegionText = $Region['province'] . $Region['city'] . $Region['district'] . $Address['address'];
		
		// 手机号码
		$mobile = model('User.Address')->where('id',$Order['addrid'])->value('mobile');
		
		if(!$Order)
		{
			$this->error('该订单不存在，请重新选择');
		}
		
		// 快递表
		$ExpressList = model('Express')->select();
		
		//
		if($this->request->isPost()){
			
			// 获取数据
			$id = $this->request->param('id');
			
			$expcode = $this->request->param('expcode');
			
			$expid = $this->request->param('expid');
			
			if(empty($expcode))
			{
				$this->error('请填写配送单号');
			}
			
			if(empty($expid))
			{
				$this->error('请选择配送快递');
			}
			
			$data = [
				'id' => $id,
				'expcode' => $expcode,
				'expid' => $expid
			];
			
			$result = model('Product.Order')->isUpdate(true)->save($data);
			
			if($result === FALSE)
			{
				$this->error('编辑失败');	
			}else{
				// cookie('LoginUser',null);
				$this->success('编辑成功',url('admin/order/order'),null,0);
			}
			
			
		}
		
		return $this->fetch('',[
				
			'ExpressList' => $ExpressList,
			
			'Order' => $Order,
			
			'RegionText' => $RegionText,
			
			'mobile' => $mobile,
			
		]);
		
	}
	
	// 填写单号
	public function uporder()
	{
		// orderid
		$orderid = $this->request->param('id');
		
		// 
		$Order = model('Product.Order')->find($orderid);
		
		// 收获地址
		$Address = model('User.Address')->where('id',$Order['addrid'])->find();
		
		$Region = model('Region')->where('code',$Address['district'])->find();
		
		$RegionText = $Region['province'] . $Region['city'] . $Region['district'] . $Address['address'];
		
		// 手机号码
		$mobile = model('User.Address')->where('id',$Order['addrid'])->value('mobile');
		
		if(!$Order)
		{
			$this->error('该订单不存在，请重新选择');
		}
		
		// 快递表
		$ExpressList = model('Express')->select();
		
		//
		if($this->request->isPost()){
			
			// 获取数据
			$id = $this->request->param('id');
			
			$expcode = $this->request->param('expcode');
			
			$expid = $this->request->param('expid');
			
			if(empty($expcode))
			{
				$this->error('请填写配送单号');
			}
			
			if(empty($expid))
			{
				$this->error('请选择配送快递');
			}
			
			$data = [
				'id' => $id,
				'expcode' => $expcode,
				'expid' => $expid,
				'status' => 2
			];
			
			$result = model('Product.Order')->isUpdate(true)->save($data);
			
			if($result === FALSE)
			{
				$this->error('填写失败');	
			}else{
				// cookie('LoginUser',null);
				$this->success('填写成功',url('admin/order/order'),null,0);
			}
			
		}
		
		// $this->view->engine->layout(false);
		
		return $this->fetch('',[
			
			'ExpressList' => $ExpressList,
			
			'orderid' => $orderid,
			
			'Order' => $Order,
			
			'RegionText' => $RegionText,
			
			'mobile' => $mobile
			
		]);
		
	}
	
}
